package jsu.ljy.lostandfind.controller;

import jsu.ljy.lostandfind.common.Result;
import jsu.ljy.lostandfind.model.ClaimInfo;
import jsu.ljy.lostandfind.model.Item;
import jsu.ljy.lostandfind.model.User;
import jsu.ljy.lostandfind.service.ItemService;
import jsu.ljy.lostandfind.service.ClaimInfoService;
import jsu.ljy.lostandfind.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * 物品管理控制器
 * 
 * <p>处理所有与物品相关的HTTP请求，包括物品的增删改查、搜索和认领等操作。</p>
 * 
 * @author 罗嘉毅
 * @version 1.0
 * @since 2024-03-21
 */
@RestController
@RequestMapping("/api/items")
public class ItemController {
    
    @Autowired
    private ItemService itemService;

    @Autowired
    private ClaimInfoService claimInfoService;

    @Autowired
    private UserService userService;

    /**
     * 获取物品列表
     * 
     * @param status 物品状态(可选)
     * @param keyword 搜索关键词(可选)
     * @return 物品列表
     */
    @GetMapping
    public Result<List<Item>> getItems(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword) {
        List<Item> items;
        if (status != null && !status.isEmpty()) {
            items = itemService.getItemsByStatus(status);
        } else if (keyword != null && !keyword.isEmpty()) {
            items = itemService.searchItems(keyword);
        } else {
            items = itemService.getAllItems();
        }
        return Result.success(items);
    }

    /**
     * 创建新物品
     * 
     * @param item 物品信息
     * @param session HTTP会话
     * @return 创建的物品信息
     */
    @PostMapping
    public Result<Item> createItem(@RequestBody Item item, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return Result.error(401, "请先登录");
        }

        item.setUserId(currentUser.getId());
        item.setCreateTime(new Date());
        itemService.publishItem(item);
        return Result.success(item);
    }

    /**
     * 获取物品详情
     * 
     * @param id 物品ID
     * @return 物品详细信息
     */
    @GetMapping("/{id}")
    public Result<Item> getItem(@PathVariable Long id) {
        Item item = itemService.getItemById(id);
        if (item != null) {
            return Result.success(item);
        }
        return Result.error(404, "物品不存在");
    }

    /**
     * 更新物品信息
     * 
     * @param id 物品ID
     * @param item 更新的物品信息
     * @param session HTTP会话
     * @return 更新后的物品信息
     */
    @PutMapping("/{id}")
    public Result<Item> updateItem(
            @PathVariable Long id,
            @RequestBody Item item,
            HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return Result.error(401, "请先登录");
        }

        Item existingItem = itemService.getItemById(id);
        if (existingItem == null) {
            return Result.error(404, "物品不存在");
        }

        if (!currentUser.getId().equals(existingItem.getUserId())) {
            return Result.error(403, "只能修改自己发布的物品");
        }

        item.setId(id);
        itemService.updateItem(item);
        return Result.success(item);
    }

    /**
     * 删除物品
     * 
     * @param id 物品ID
     * @param session HTTP会话
     * @return 无返回内容
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteItem(@PathVariable Long id, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return Result.error(401, "请先登录");
        }

        Item item = itemService.getItemById(id);
        if (item == null) {
            return Result.error(404, "物品不存在");
        }

        if (!currentUser.getId().equals(item.getUserId())) {
            return Result.error(403, "只能删除自己发布的物品");
        }

        itemService.deleteItem(id);
        return Result.success(null);
    }

    /**
     * 搜索物品
     * 
     * @param keyword 搜索关键词
     * @return 匹配的物品列表
     */
    @GetMapping("/search")
    public Result<List<Item>> searchItems(@RequestParam String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return Result.success(itemService.getAllItems());
        }
        return Result.success(itemService.searchItems(keyword.trim()));
    }

    /**
     * 认领物品
     * 
     * @param id 物品ID
     * @param claimInfo 认领信息
     * @param session HTTP会话
     * @return 认领后的物品信息
     */
    @PostMapping("/{id}/claim")
    public Result<Item> claimItem(@PathVariable Long id, @RequestBody ClaimInfo claimInfo, HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return Result.error(401, "请先登录");
        }

        Item item = itemService.getItemById(id);
        if (item == null) {
            return Result.error(404, "物品不存在");
        }

        // 只能认领招领启事的物品
        if (!"FOUND".equals(item.getStatus())) {
            return Result.error(400, "该物品不可认领");
        }

        // 不能认领自己发布的物品
        if (currentUser.getId().equals(item.getUserId())) {
            return Result.error(400, "不能认领自己发布的物品");
        }

        // 检查是否已有认领记录
        List<ClaimInfo> existingClaims = claimInfoService.getClaimInfosByItemId(id);
        if (!existingClaims.isEmpty()) {
            return Result.error(400, "该物品已被认领");
        }

        // 验证认领信息
        if (claimInfo.getRealName() == null || claimInfo.getRealName().trim().isEmpty()) {
            return Result.error(400, "请填写真实姓名");
        }
        if (claimInfo.getStudentId() == null || claimInfo.getStudentId().trim().isEmpty()) {
            return Result.error(400, "请填写学号");
        }
        if (claimInfo.getPhone() == null || claimInfo.getPhone().trim().isEmpty()) {
            return Result.error(400, "请填写联系电话");
        }

        // 保存认领信息
        claimInfo.setItemId(id);
        claimInfo.setUserId(currentUser.getId());
        claimInfo.setCreateTime(new Date());
        claimInfo.setStatus("PENDING"); // 设置为待处理状态
        claimInfoService.save(claimInfo);

        // 更新物品状态为待确认
        item.setStatus("PENDING_CLAIM");
        itemService.updateItem(item);

        return Result.success(item);
    }

    /**
     * 获取物品的认领记录
     * 
     * @param id 物品ID
     * @return 认领记录列表
     */
    @GetMapping("/{id}/claims")
    public Result<List<ClaimInfo>> getItemClaims(@PathVariable Long id) {
        Item item = itemService.getItemById(id);
        if (item == null) {
            return Result.error(404, "物品不存在");
        }

        List<ClaimInfo> claims = claimInfoService.getClaimInfosByItemId(id);
        // 填充认领用户信息
        for (ClaimInfo claim : claims) {
            User user = userService.getUserById(claim.getUserId());
            claim.setUser(user);
        }
        return Result.success(claims);
    }

    // 添加处理认领申请的接口
    @PostMapping("/claims/{claimId}/handle")
    public Result<ClaimInfo> handleClaim(
            @PathVariable Long claimId,
            @RequestParam String status,
            HttpSession session) {
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            return Result.error(401, "请先登录");
        }

        ClaimInfo claim = claimInfoService.getClaimInfoById(claimId);
        if (claim == null) {
            return Result.error(404, "认领记录不存在");
        }

        Item item = itemService.getItemById(claim.getItemId());
        if (item == null) {
            return Result.error(404, "物品不存在");
        }

        // 只有物品发布者可以处理认领申请
        if (!currentUser.getId().equals(item.getUserId())) {
            return Result.error(403, "无权处理该认领申请");
        }

        // 更新认领状态
        claim.setStatus(status);
        claimInfoService.update(claim);

        // 更新物品状态
        if ("APPROVED".equals(status)) {
            item.setStatus("CLAIMED");
            item.setClaimUserId(claim.getUserId());
            item.setClaimTime(new Date());
        } else if ("REJECTED".equals(status)) {
            item.setStatus("FOUND");
            item.setClaimUserId(null);
            item.setClaimTime(null);
        }
        itemService.updateItem(item);

        return Result.success(claim);
    }
} 